package com.atguigu.commonutils.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class LoginUserUtil {

    /**
     * 获取token
     */
    public static String getToken() {
        HttpServletRequest request = HttpContext.getRequest();
        return request.getHeader("Authorization");
    }

    /**
     * 获取登录用户ID
     */
    public static String getLoginUserId() {
        String token = getToken();
        if (StringUtils.isNotEmpty(token)) {
            String userId = JwtTokenUtil.getUserIdFromToken(token);
            if (StringUtils.isNotEmpty(userId)) {
                return userId;
            }
        }
        throw new GuliException(20001, "登录超时");
    }

    /**
     * 获取登录用户
     */
    @SuppressWarnings("unchecked")
    public static LoginUser getLoginUser() {
        String userId = getLoginUserId();
        return getLoginUser(userId);
    }

    /**
     * 获取登录用户
     */
    @SuppressWarnings("unchecked")
    public static LoginUser getLoginUser(String userId) {
        RedisTemplate<String, LoginUser> jsonRedisTemplate =
                (RedisTemplate<String, LoginUser>) SpringContextUtil.getBean("jsonRedisTemplate");
        LoginUser loginUser = jsonRedisTemplate.opsForValue().get(String.format("alan:loginUser:%s", userId));
        if (loginUser == null) {
            throw new GuliException(20001, "登录超时");
        }
        return loginUser;
    }
}
